﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Tracy.Agent.DownloaderAdapter;

namespace Tracy.Engine
{
    public class PluginManager
    {
        private Dictionary<string, Type> downloaderAdapters;
        private string pluginFolder;

        public string PluginFolder
        {
            get { return pluginFolder; }
        }

        private Dictionary<string, Type> DownloaderAdapters
        {
            get { if (downloaderAdapters == null)downloaderAdapters = new Dictionary<string, Type>(); return downloaderAdapters; }
        }

        public PluginManager(string pluginFolder)
        {
            //设置程序集加载目录
            this.pluginFolder = pluginFolder;
        }

        public void LoadPlugins()
        {
            string folderFullName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pluginFolder;
            //TODO:更改搜索条件
            foreach (string pluginPath in System.IO.Directory.GetFiles(folderFullName,"*Adapter.dll", System.IO.SearchOption.AllDirectories))
            {
                LoadPlugin(pluginPath);
            }
        }

        public void LoadPlugin(string fullPath)
        {
            Assembly pluginAssembly = Assembly.LoadFile(fullPath);
            Type pluginType = pluginAssembly.GetTypes()[0];
            foreach (Type t in pluginType.GetInterfaces())
            {
                if (t == typeof(IDownloaderAdapter)) DownloaderAdapters.Add(pluginType.Name, pluginType);
            }
        }

        public IDownloaderAdapter CreateDownloaderAdapter(string name)
        {
            Type adapterType = DownloaderAdapters[name];
            
            return (IDownloaderAdapter)Activator.CreateInstance(adapterType);
        }
    }
}
